﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using static DM_TOOLS.Tools.CSVFileWatch;

namespace DM_TOOLS.Tools.SMTP
{
    public static class SMTPWarnContent
    {
        /// <summary>
        /// 识别文件里是否有加速度和位移超标值并返回信息
        /// </summary>
        /// <param name="cSVFileWatchStruct"></param>
        /// <param name="vehicle"></param>
        /// <param name="accerror"></param>
        /// <param name="diserror"></param>
        /// <returns></returns>
        public static string CreateWarnContent(CSVFileWatchStruct cSVFileWatchStruct, string vehicle, int accerror,int diserror, int frontdis,int reardis)
        {
            string errormessage = "";
           
            foreach (string header in cSVFileWatchStruct.headers)
            {
                if (header.Contains("acc") && (!header.Contains("acce")))
                {
                    var idx = cSVFileWatchStruct.headers.IndexOf(header);
                    var acc = cSVFileWatchStruct.alldatalist[idx].Any(a =>Math.Abs(a)>= accerror);
                    if (acc)
                    {
                        errormessage += $"{vehicle}的{header}通道出现了大于{accerror}的问题\n";
                        break;
                    }
                }
                if (header.Contains("disdmp")&& (header.Contains("lf")|| header.Contains("rf")))
                {
                    var idx = cSVFileWatchStruct.headers.IndexOf(header);
                    var dis = Math.Abs(cSVFileWatchStruct.alldatalist[idx].Average()- frontdis)> diserror;
                    if (dis)
                    {
                        errormessage += $"{vehicle}的{header}通道均值偏离标准值过大\n";
                        break;
                    }
                }
                if (header.Contains("disdmp") && (header.Contains("lr") || header.Contains("rr")))
                {
                    var idx = cSVFileWatchStruct.headers.IndexOf(header);
                    var dis = Math.Abs(cSVFileWatchStruct.alldatalist[idx].Average() - reardis) > diserror;
                    if (dis)
                    {
                        errormessage += $"{vehicle}的{header}通道均值偏离标准值过大\n";
                        break;
                    }
                }
            }
            return errormessage;
        }

        /// <summary>
        /// 识别信号字典中是否有加速度和位移超标值，并返回提示信息，这个不是监控log的
        /// </summary>
        /// <param name="signalData">Key: 通道名，Value: (Time, Value) 列表</param>
        /// <param name="vehicle">车辆名</param>
        /// <param name="accerror">加速度阈值</param>
        /// <param name="diserror">位移偏差阈值</param>
        /// <param name="frontdis">前轮标准位移</param>
        /// <param name="reardis">后轮标准位移</param>
        /// <returns>返回提示信息字符串，如果没有异常返回空字符串</returns>
        public static string CreateWarnContent(
            Dictionary<string, List<(double Time, double Value)>> signalData,
            string vehicle,
            int accerror,
            int diserror,
            int frontdis,
            int reardis)
        {
            string errormessage = "";

            foreach (var kvp in signalData)
            {
                string header = kvp.Key;
                var values = kvp.Value.Select(x => x.Value).ToList(); // 只取 Value 列

                // 处理加速度通道
                if (header.Contains("acc") && !header.Contains("acce"))
                {
                    bool accExceeded = values.Any(a => Math.Abs(a) >= accerror);
                    if (accExceeded)
                    {
                        errormessage += $"{vehicle}的{header}通道出现了大于{accerror}的问题\n";
                        break; // 找到第一个就跳出
                    }
                }

                // 前轮位移通道
                if (header.Contains("disdmp") && (header.Contains("lf") || header.Contains("rf")))
                {
                    double avg = values.Average();
                    bool disExceeded = Math.Abs(avg - frontdis) > diserror;
                    if (disExceeded)
                    {
                        errormessage += $"{vehicle}的{header}通道均值偏离标准值过大\n";
                        break;
                    }
                }

                // 后轮位移通道
                if (header.Contains("disdmp") && (header.Contains("lr") || header.Contains("rr")))
                {
                    double avg = values.Average();
                    bool disExceeded = Math.Abs(avg - reardis) > diserror;
                    if (disExceeded)
                    {
                        errormessage += $"{vehicle}的{header}通道均值偏离标准值过大\n";
                        break;
                    }
                }
            }

            return errormessage;
        }

        /// <summary>
        /// 识别日志里是否有错误信息并返回
        /// </summary>
        /// <param name="contents">日志信息</param>
        /// <param name="keywords">错误关键词</param>
        /// <param name="logfilename">日志文件名</param>
        /// <returns></returns>
        public static string CreateWarnContentforLog(string[] contents, string[] keywords, int can0, int idcount, string logfilename)
        {
            string errormessage = "";
            //这一部分是查看有没有出现关键字
            var matchingElements = contents.SelectMany(s => keywords.Where(k => s.Contains(k)).Select(k => new { Element = s, Keyword = k }));
            if (matchingElements.Count() > 0)
            {
                foreach (var match in matchingElements)
                {
                    errormessage += $"{logfilename}的元素 '{match.Element}' 包含关键字 '{match.Keyword}'。" + Environment.NewLine;
                }
                //判断是否出现ValueError错误
                if (errormessage.Contains("ValueError"))
                {
                    errormessage += $"此车辆需要立刻重启！！！" + Environment.NewLine;
                }
            }
            //这一段是为了查看是否小于标准值，跟前面没有关系
            string pattern1 = @"data:\s(\d+)";
            string pattern2 = @"can0:\s(\d+)";
            Regex regex1 = new Regex(pattern1);
            foreach (string content in contents)
            {
                Match match1 = regex1.Match(content);
                if (match1.Success)
                {
                    string data1 = match1.Groups[1].Value;
                    bool su = int.TryParse(data1, out int r);
                    if (su)
                    {
                        if (r < idcount)
                        {
                            errormessage += $"{logfilename} 的id数量 {r} 小于标准值 {idcount}。" + Environment.NewLine;
                            break;
                        }
                    }

                }
            }
            Regex regex2 = new Regex(pattern2);
            foreach (string content in contents)
            {
                Match match2 = regex2.Match(content);
                if (match2.Success)
                {
                    string data2 = match2.Groups[1].Value;
                    bool su = int.TryParse(data2, out int r);
                    if (su)
                    {
                        if (r < can0)
                        {
                            errormessage += $"{logfilename} 的can0数据量 {r} 小于标准值 {can0}。" + Environment.NewLine;
                            break;
                        }
                    }

                }
            }
            return errormessage;
        }
        public static bool IsPastOneHour(DateTime startTime, int timespan)
        {
            // 获取当前时间
            DateTime currentTime = DateTime.Now;
            // 计算时间间隔
            TimeSpan timeElapsed = currentTime - startTime;
            // 判断是否过了1小时
            if (timeElapsed.TotalMinutes >= timespan)
            {
                return true;
            }

            return false;
        }

    }
}
